import React from 'react'
import { Menu } from 'antd'
import styles from './index.module.less'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import { useStore } from '@/store'
import type { MenuProps } from 'antd/es/menu'
import { useState } from 'react'
import { Menu as IMenu } from '@/types/api'
import * as Icons from '@ant-design/icons'
import { useMount } from 'ahooks'

const SideMenu = () => {
  const [menuList, setMenuList] = useState<MenuItem[]>([])
  const navigate = useNavigate()
  const { collapsed, isDark } = useStore(state => ({
    collapsed: state.collapsed, // 伸展
    isDark: state.isDark // 是否深色
  }))
  const data: any = useRouteLoaderData('layout')
  const [selectedKeys, setSelectedKeys] = useState<string[]>([])
  const { pathname } = useLocation()
  type MenuItem = Required<MenuProps>['items'][number]

  // 生成每一个菜单项
  function getItem(
    label: React.ReactNode,
    key?: React.Key | null,
    icon?: React.ReactNode,
    children?: MenuItem[]
  ): MenuItem {
    return {
      label,
      key,
      icon,
      children
    } as MenuItem
  }
  // 图标
  function createIcon(name?: string) {
    if (!name) return <></>
    const customerIcons: { [key: string]: any } = Icons // ****
    const icon = customerIcons[name]
    if (!icon) return <></>
    return React.createElement(icon)
  }
  // 递归生成菜单 ****
  const getTreeMenu = (menuList: IMenu.MenuItem[], treeList: MenuItem[] = []) => {
    menuList.forEach((item, index) => {
      if (item.menuType === 1 && item.menuState === 1) {
        if (!item?.children?.length || item.buttons) {
          return treeList.push(getItem(item.menuName, item.path || index, createIcon(item.icon)))
        }
        treeList.push(
          getItem(item.menuName, item.path || index, createIcon(item.icon), getTreeMenu(item.children || []))
        )
      }
    })
    return treeList
  }
  // 初始化，获取接口菜单列表数据
  useMount(() => {
    const treeMenuList = getTreeMenu(data.menuList)
    setMenuList(treeMenuList)
    setSelectedKeys([pathname])
  })

  return (
    <div className={styles.navSide}>
      <div className={styles.logo} onClick={() => navigate('/welcome')}>
        <img src='/imgs/logo.png' className={styles.img} />
        {collapsed ? null : <span>通用管理后台</span>}
      </div>
      <Menu
        mode='inline'
        theme={isDark ? 'light' : 'dark'} // 反取
        style={{
          // width: collapsed ? 80 : 'auto',
          height: 'calc(100vh - 50px)'
        }}
        selectedKeys={selectedKeys}
        onClick={({ key }: { key: string }) => {
          setSelectedKeys([key])
          navigate(key)
        }}
        items={menuList}
        inlineCollapsed={collapsed}
      />
    </div>
  )
}

export default SideMenu
